/**
 * 
 */
package org.vectrics.recruiter.struts.admin.file;

import java.io.InputStream;

import org.apache.log4j.Logger;
import org.vectrics.SystemException;
import org.vectrics.hibernate.ThreadProperties;
import org.vectrics.recruiter.RecruitServiceLocator;
import org.vectrics.recruiter.user.CandidateInfo;
import org.vectrics.recruiter.user.Resume;
import org.vectrics.user.Person;

/**
 * @author pgoette
 * Clase encargada de subir un archivo
 */
public class UploadFileHelper {
	
	private transient Logger log = Logger.getLogger(this.getClass()); 
	
	public void execute(InputStream uploadStream, String fileName, String category, String originalFileName, Person person) {
		try {
			// Si es un cv lo guardo como tal
			if (category.trim().equalsIgnoreCase("resume")) {
				CandidateInfo candidate = RecruitServiceLocator.getRecruitUserService().createCandidateInfoIfNotExist(person);
			    if (candidate.getId() == null) {
			    	RecruitServiceLocator.getRecruitUserService().updateCandidateInfo(candidate);
			    }
		
				Resume resume = candidate.addResume();
				resume.setName(fileName);
				
				RecruitServiceLocator.getRecruitUserService().saveResumeToFile(
						candidate, resume, originalFileName, uploadStream);
			} else {
				// Si no es un cv guardo el archivo comun.
				RecruitServiceLocator.getRecruitUserService().saveFile(
						person, category, originalFileName, uploadStream, fileName);
			}
			ThreadProperties.forcedCommit();
			log.info("File saved successfully");
		} catch (Exception ex) {
			log.error("Exception saving file to server drive", ex);
			throw new SystemException("Exception saving file to server drive", ex);
		}
	}
	
}
